<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>部门管理 - 人事管理系统</title>
    <!-- 引入Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- 引入Bootstrap图标 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        .navbar-brand {
            font-weight: bold;
            font-size: 1.5rem;
        }
        .footer {
            margin-top: 50px;
            padding: 20px 0;
            color: #6c757d;
            border-top: 1px solid #dee2e6;
        }
        .table-actions {
            white-space: nowrap;
        }
        .search-bar {
            margin-bottom: 20px;
        }
        .pagination {
            justify-content: center;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <div th:replace="~{layout/header :: navbar(active='dept')}"></div>

    <!-- 主要内容 -->
    <div class="container mt-4">
        <div class="row">
            <div class="col-md-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2>部门管理</h2>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addDeptModal">
                        <i class="bi bi-plus-circle me-1"></i>新增部门
                    </button>
                </div>
                
                <!-- 搜索栏 -->
                <div class="card search-bar">
                    <div class="card-body">
                        <form id="searchForm" class="row g-3">
                            <div class="col-md-4">
                                <label for="deptName" class="form-label">部门名称</label>
                                <input type="text" class="form-control" id="deptName" name="name" placeholder="请输入部门名称">
                            </div>
                            <div class="col-md-4 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary me-2">
                                    <i class="bi bi-search me-1"></i>搜索
                                </button>
                                <button type="button" class="btn btn-secondary" id="resetBtn">
                                    <i class="bi bi-arrow-counterclockwise me-1"></i>重置
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                
                <!-- 部门列表 -->
                <div class="card">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>部门名称</th>
                                        <th>部门编号</th>
                                        <th>员工人数</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="deptTableBody">
                                    <!-- 部门数据将通过JavaScript动态加载 -->
                                </tbody>
                            </table>
                        </div>
                        
                        <!-- 分页 -->
                        <nav aria-label="Page navigation">
                            <ul class="pagination" id="pagination">
                                <!-- 分页将通过JavaScript动态生成 -->
                            </ul>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 新增部门模态框 -->
    <div class="modal fade" id="addDeptModal" tabindex="-1" aria-labelledby="addDeptModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addDeptModalLabel">新增部门</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="addDeptForm">
                        <div class="mb-3">
                            <label for="addDeptName" class="form-label">部门名称</label>
                            <input type="text" class="form-control" id="addDeptName" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label for="addDeptNumber" class="form-label">部门编号</label>
                            <input type="number" class="form-control" id="addDeptNumber" name="number" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveDeptBtn">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑部门模态框 -->
    <div class="modal fade" id="editDeptModal" tabindex="-1" aria-labelledby="editDeptModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editDeptModalLabel">编辑部门</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editDeptForm">
                        <input type="hidden" id="editDeptId" name="id">
                        <div class="mb-3">
                            <label for="editDeptName" class="form-label">部门名称</label>
                            <input type="text" class="form-control" id="editDeptName" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label for="editDeptNumber" class="form-label">部门编号</label>
                            <input type="number" class="form-control" id="editDeptNumber" name="number" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="updateDeptBtn">更新</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 查看部门员工模态框 -->
    <div class="modal fade" id="viewEmployeesModal" tabindex="-1" aria-labelledby="viewEmployeesModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="viewEmployeesModalLabel">部门员工列表</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>工号</th>
                                    <th>姓名</th>
                                    <th>性别</th>
                                    <th>年龄</th>
                                </tr>
                            </thead>
                            <tbody id="employeeTableBody">
                                <!-- 员工数据将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 确认删除模态框 -->
    <div class="modal fade" id="deleteDeptModal" tabindex="-1" aria-labelledby="deleteDeptModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteDeptModalLabel">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>您确定要删除这个部门吗？此操作不可逆。</p>
                    <input type="hidden" id="deleteDeptId">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmDeleteBtn">删除</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <div th:replace="~{layout/footer :: footer}"></div>
    
    <!-- 通用脚本 -->
    <div th:replace="~{layout/footer :: scripts}"></div>
    
    <!-- 部门管理脚本 -->
    <script>
        $(document).ready(function() {
            // 当前页码和每页数量
            let currentPage = 1;
            const pageSize = 10;
            
            // 加载部门列表
            function loadDepartments(page = 1, name = '') {
                // 构建查询参数
                const params = {
                    page: page,
                    pageSize: pageSize
                };
                
                if (name) {
                    params.name = name;
                }
                
                // 发送AJAX请求获取部门列表
                $.ajax({
                    url: '/depts',
                    type: 'GET',
                    data: params,
                    success: function(response) {
                        if (response.code === 1) {
                            const pageResult = response.data;
                            const departments = pageResult.records;
                            
                            // 更新当前页码
                            currentPage = pageResult.page;
                            
                            // 清空表格
                            $('#deptTableBody').empty();
                            
                            // 遍历部门数据，构建表格行
                            if (departments && departments.length > 0) {
                                departments.forEach(function(dept) {
                                    const row = `
                                        <tr>
                                            <td>${dept.id}</td>
                                            <td>${dept.name}</td>
                                            <td>${dept.number}</td>
                                            <td>${dept.employeeCount || 0}</td>
                                            <td class="table-actions">
                                                <button class="btn btn-sm btn-info view-employees" data-id="${dept.id}" data-name="${dept.name}">
                                                    <i class="bi bi-people"></i> 查看员工
                                                </button>
                                                <button class="btn btn-sm btn-primary edit-dept" data-id="${dept.id}">
                                                    <i class="bi bi-pencil"></i> 编辑
                                                </button>
                                                <button class="btn btn-sm btn-danger delete-dept" data-id="${dept.id}">
                                                    <i class="bi bi-trash"></i> 删除
                                                </button>
                                            </td>
                                        </tr>
                                    `;
                                    $('#deptTableBody').append(row);
                                });
                            } else {
                                $('#deptTableBody').append('<tr><td colspan="5" class="text-center">暂无数据</td></tr>');
                            }
                            
                            // 生成分页
                            generatePagination(pageResult.total, pageResult.page, pageResult.pageSize, pageResult.pages);
                        } else {
                            alert('加载部门列表失败：' + response.msg);
                        }
                    },
                    error: function() {
                        alert('加载部门列表失败，请稍后再试');
                    }
                });
            }
            
            // 生成分页
            function generatePagination(total, currentPage, pageSize, totalPages) {
                const $pagination = $('#pagination');
                $pagination.empty();
                
                // 如果总页数小于等于1，不显示分页
                if (totalPages <= 1) {
                    return;
                }
                
                // 上一页按钮
                const $prevItem = $('<li class="page-item">').toggleClass('disabled', currentPage === 1);
                const $prevLink = $('<a class="page-link" href="javascript:void(0);" aria-label="Previous">')
                    .append('<span aria-hidden="true">&laquo;</span>');
                $prevItem.append($prevLink);
                $pagination.append($prevItem);
                
                // 页码按钮
                const startPage = Math.max(1, currentPage - 2);
                const endPage = Math.min(totalPages, startPage + 4);
                
                for (let i = startPage; i <= endPage; i++) {
                    const $pageItem = $('<li class="page-item">').toggleClass('active', i === currentPage);
                    const $pageLink = $('<a class="page-link" href="javascript:void(0);">').text(i);
                    $pageItem.append($pageLink);
                    $pagination.append($pageItem);
                }
                
                // 下一页按钮
                const $nextItem = $('<li class="page-item">').toggleClass('disabled', currentPage === totalPages);
                const $nextLink = $('<a class="page-link" href="javascript:void(0);" aria-label="Next">')
                    .append('<span aria-hidden="true">&raquo;</span>');
                $nextItem.append($nextLink);
                $pagination.append($nextItem);
                
                // 绑定分页点击事件
                $pagination.find('.page-link').click(function() {
                    const $this = $(this);
                    const $parent = $this.parent();
                    
                    // 如果是禁用状态或当前页，不处理
                    if ($parent.hasClass('disabled') || $parent.hasClass('active')) {
                        return;
                    }
                    
                    let targetPage = currentPage;
                    
                    // 上一页
                    if ($this.attr('aria-label') === 'Previous') {
                        targetPage = currentPage - 1;
                    }
                    // 下一页
                    else if ($this.attr('aria-label') === 'Next') {
                        targetPage = currentPage + 1;
                    }
                    // 具体页码
                    else {
                        targetPage = parseInt($this.text());
                    }
                    
                    // 加载目标页数据
                    const name = $('#deptName').val();
                    loadDepartments(targetPage, name);
                });
            }
            
            // 初始加载部门列表
            loadDepartments();
            
            // 搜索表单提交
            $('#searchForm').submit(function(event) {
                event.preventDefault();
                const name = $('#deptName').val();
                loadDepartments(1, name);
            });
            
            // 重置按钮点击事件
            $('#resetBtn').click(function() {
                $('#deptName').val('');
                loadDepartments();
            });
            
            // 保存新部门
            $('#saveDeptBtn').click(function() {
                const name = $('#addDeptName').val();
                const number = $('#addDeptNumber').val();
                
                if (!name || !number) {
                    alert('请填写完整的部门信息');
                    return;
                }
                
                const deptData = {
                    name: name,
                    number: parseInt(number)
                };
                
                $.ajax({
                    url: '/depts',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(deptData),
                    success: function(response) {
                        if (response.code === 1) {
                            // 关闭模态框
                            $('#addDeptModal').modal('hide');
                            // 重置表单
                            $('#addDeptForm')[0].reset();
                            // 重新加载部门列表
                            loadDepartments();
                            alert('部门添加成功');
                        } else {
                            alert('部门添加失败：' + response.msg);
                        }
                    },
                    error: function() {
                        alert('部门添加失败，请稍后再试');
                    }
                });
            });
            
            // 编辑部门按钮点击事件
            $(document).on('click', '.edit-dept', function() {
                const deptId = $(this).data('id');
                
                // 获取部门详情
                $.ajax({
                    url: '/depts/' + deptId,
                    type: 'GET',
                    success: function(response) {
                        if (response.code === 1) {
                            const dept = response.data;
                            $('#editDeptId').val(dept.id);
                            $('#editDeptName').val(dept.name);
                            $('#editDeptNumber').val(dept.number);
                            $('#editDeptModal').modal('show');
                        } else {
                            alert('获取部门详情失败：' + response.msg);
                        }
                    },
                    error: function() {
                        alert('获取部门详情失败，请稍后再试');
                    }
                });
            });
            
            // 更新部门
            $('#updateDeptBtn').click(function() {
                const id = $('#editDeptId').val();
                const name = $('#editDeptName').val();
                const number = $('#editDeptNumber').val();
                
                if (!name || !number) {
                    alert('请填写完整的部门信息');
                    return;
                }
                
                const deptData = {
                    id: parseInt(id),
                    name: name,
                    number: parseInt(number)
                };
                
                $.ajax({
                    url: '/depts',
                    type: 'PUT',
                    contentType: 'application/json',
                    data: JSON.stringify(deptData),
                    success: function(response) {
                        if (response.code === 1) {
                            // 关闭模态框
                            $('#editDeptModal').modal('hide');
                            // 重新加载部门列表
                            loadDepartments(currentPage);
                            alert('部门更新成功');
                        } else {
                            alert('部门更新失败：' + response.msg);
                        }
                    },
                    error: function() {
                        alert('部门更新失败，请稍后再试');
                    }
                });
            });
            
            // 删除部门按钮点击事件
            $(document).on('click', '.delete-dept', function() {
                const deptId = $(this).data('id');
                $('#deleteDeptId').val(deptId);
                $('#deleteDeptModal').modal('show');
            });
            
            // 确认删除部门
            $('#confirmDeleteBtn').click(function() {
                const deptId = $('#deleteDeptId').val();
                
                $.ajax({
                    url: '/depts/' + deptId,
                    type: 'DELETE',
                    success: function(response) {
                        if (response.code === 1) {
                            // 关闭模态框
                            $('#deleteDeptModal').modal('hide');
                            // 重新加载部门列表
                            loadDepartments(currentPage);
                            alert('部门删除成功');
                        } else {
                            alert('部门删除失败：' + response.msg);
                        }
                    },
                    error: function() {
                        alert('部门删除失败，请稍后再试');
                    }
                });
            });
            
            // 查看部门员工按钮点击事件
            $(document).on('click', '.view-employees', function() {
                const deptId = $(this).data('id');
                const deptName = $(this).data('name');
                
                // 更新模态框标题
                $('#viewEmployeesModalLabel').text(deptName + ' - 员工列表');
                
                // 获取部门员工列表
                $.ajax({
                    url: '/depts/emps/' + deptId,
                    type: 'GET',
                    success: function(response) {
                        if (response.code === 1) {
                            const employees = response.data;
                            
                            // 清空表格
                            $('#employeeTableBody').empty();
                            
                            // 遍历员工数据，构建表格行
                            if (employees && employees.length > 0) {
                                employees.forEach(function(emp) {
                                    const row = `
                                        <tr>
                                            <td>${emp.id}</td>
                                            <td>${emp.number}</td>
                                            <td>${emp.name}</td>
                                            <td>${emp.gender}</td>
                                            <td>${emp.age}</td>
                                        </tr>
                                    `;
                                    $('#employeeTableBody').append(row);
                                });
                            } else {
                                $('#employeeTableBody').append('<tr><td colspan="5" class="text-center">该部门暂无员工</td></tr>');
                            }
                            
                            // 显示模态框
                            $('#viewEmployeesModal').modal('show');
                        } else {
                            alert('获取部门员工列表失败：' + response.msg);
                        }
                    },
                    error: function() {
                        alert('获取部门员工列表失败，请稍后再试');
                    }
                });
            });
        });
    </script>
</body>
</html> 